/* $Id: LoginDialogBox.java 138 2011-09-01 17:51:37Z altdotua@gmail.com $ */

package alt.djudge.frontend.client.ui;

import alt.djudge.frontend.client.ui.contest.Layout;
import alt.djudge.frontend.shared.dto.contest.UserLoginInfo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;


public class LoginDialogBox extends DialogBox
{
	interface MyUiBinder extends UiBinder<Widget, LoginDialogBox> {}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	@UiField
	TextBox txtUsername;
	
	@UiField
	PasswordTextBox txtPassword;
	
	@UiField
	Button btnCancel;
	
	@UiField
	Button btnLogin;
	
	@UiField
	Label lblError;
	
	public LoginDialogBox()
	{
		setWidget(uiBinder.createAndBindUi(this));
		setTitle("Login");
		
		btnCancel.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				hide();
				History.back();
			}
		});
		
		btnLogin.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				if (txtUsername.getText().length() == 0)
				{
					lblError.setText("Username must be non-empty");
					return;
				}
				if (txtPassword.getText().length() == 0)
				{
					lblError.setText("Password must be non-empty");
					return;
				}
				lblError.setText("");
				AsyncCallback<UserLoginInfo> callback = new AsyncCallback<UserLoginInfo>()
				{
					@Override
					public void onSuccess(UserLoginInfo loginInfo)
					{
						if (loginInfo != null)
						{
    						AbstractLayout.getLayout().setSessionId(loginInfo.getSessionId());
    						AbstractLayout.getLayout().setLoginInfo(loginInfo);
    						hide();
    						History.back();
						}
						else
						{
							lblError.setText("Wrong username of password");
						}
					}
					
					@Override
					public void onFailure(Throwable caught)
					{
						lblError.setText("Server error. Please, try again later");
					}
				};
				
				Layout.loginService.doLogin(txtUsername.getText(), txtPassword.getText(), callback);
			}
		});
	};	
}
